<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DestinationModel;
use App\Models\FlightModel;
use App\Models\lazada\ApiModel;
use App\Models\lazada\LogModel;
use App\Models\lazada\OrderModel;
use App\Models\lazada\CallBackModel;
use App\Models\lazada\BigBagModel;
use App\Http\Requests\customer\CallBackRequest;
use App\Models\customer\NodeModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;


class CallBack extends Controller
{
    use CallBackRequest;

    // 预发：nbf-gateway-open-api.aidc-dchain.com
    // 正式：aidc-nbf.ap-southeast-1.aliyuncs.com
    protected $host = 'aidc-nbf.ap-southeast-1.aliyuncs.com';
    protected $gatewayApiCode = [
        'delivery_line_haul_pick_up_callback' => 'glcDeliveryLineHaulPickUpCallback',
        'delivery_line_haul_pre_booking_callback' => 'glcDeliveryLineHaulPreBookingCallback',
        'transit_line_haul_departure_callback' => 'glcTransitLinehaulDepartureCallback',
        'customs_cc_ex_start_callback' => 'glcCustomsCcExStartCallback',
        'customs_cc_ex_failure_callback' => 'glcCustomsCcExFailureCallback',
        'customs_cc_ex_success_callback' => 'glcCustomsCcExSuccessCallback',
        'line_haul_ho_airline_failed_callback' => 'glcLineHaulHoAirlineFailedCallback',
        'delivery_line_haul_exception_callback' => 'glcDeliveryLineHaulExceptionCallback',
        'delivery_line_haul_ho_airline_callback' => 'glcDeliveryLineHaulHoAirlineCallback',
        'delivery_line_haul_departure_callback' => 'glcDeliveryLineHaulDepartureCallback',
        'delivery_line_haul_arrival_callback' => 'glcDeliveryLineHaulArrivalCallback',
        'customs_cc_im_start_callback' => 'glcCustomsCcImStartCallback',
        'customs_cc_im_abnormal_callback' => 'glcCustomsCcImAbnormalCallback',
        'customs_cc_im_success_callback' => 'glcCustomsCcImSuccessCallback',
        'customs_ho_out_success_callback' => 'glcCustomsHoOutSuccessCallback',
        'common_bigbag_callback' => 'glcCommonBigbagCallback',
        'delivery_line_haul_mawb_callback' => 'GlcDeliveryLineHaulMawbCallback',

    ];

    protected $data = [];

    public function callback_test(Request $request)
    {
        $data = $request->all();
        $this->data = $data;

        if($data['gatewayApiCode'] == 'glcDeliveryLineHaulPickUpCallback'){
            $res = $this->delivery_line_haul_pick_up_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcDeliveryLineHaulPreBookingCallback'){
            $res = $this->delivery_line_haul_pre_booking_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcTransitLinehaulDepartureCallback'){
            $res = $this->transit_line_haul_departure_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcCustomsCcExStartCallback'){
            $res =$this->customs_cc_ex_start_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcCustomsCcExFailureCallback'){
            $res = $this->customs_cc_ex_failure_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcCustomsCcExSuccessCallback'){
            $res = $this->customs_cc_ex_success_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcLineHaulHoAirlineFailedCallback'){
            $res = $this->line_haul_ho_airline_failed_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcDeliveryLineHaulExceptionCallback'){
            $res = $this->delivery_line_haul_exception_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcDeliveryLineHaulHoAirlineCallback'){
            $res = $this->delivery_line_haul_ho_airline_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcDeliveryLineHaulDepartureCallback'){
            $res = $this->delivery_line_haul_departure_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcDeliveryLineHaulArrivalCallback'){
            $res = $this->delivery_line_haul_arrival_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcCustomsCcImStartCallback'){
            $res = $this->customs_cc_im_start_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcCustomsCcImAbnormalCallback'){
            $res = $this->customs_cc_im_abnormal_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcCustomsCcImSuccessCallback'){
            $res = $this->customs_cc_im_success_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcCustomsHoOutSuccessCallback'){
            $res = $this->customs_ho_out_success_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcCommonBigbagCallback'){
            $res = $this->common_bigbag_callback($data['order_id']);
        }else if($data['gatewayApiCode'] == 'glcDeliveryLineHaulMawbCallback'){
            $res = $this->delivery_line_haul_mawb_callback($data['order_id']);
        }else{
            return ['result' => false, 'msg' => '接口不存在'];
        }


        return $this->success($res);
    }

    /**
     * Notes:仓配交接 (揽收成功)(glcDeliveryLineHaulPickUpCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function delivery_line_haul_pick_up_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['delivery_line_haul_pick_up_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['delivery_line_haul_pick_up_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }


    /**
     * Notes:干线提单配舱(glcDeliveryLineHaulPreBookingCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function delivery_line_haul_pre_booking_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

//        $take_order = TakeOrderModel::find($order->take_order_id);
//        if(!$take_order){
//            return ['result' => false, 'msg' => '提单不存在'];
//        }
//
//        $flight = $take_order->flight;
//        if(!$flight){
//            return ['result' => false, 'msg' => '提单未配航班运力'];
//        }
//
//        $flight_line = $flight->items->first();
//        if(!$flight_line){
//            return ['result' => false, 'msg' => '提单未配航线'];
//        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0',
//            'fromPortCode' => $flight_line->start_port->code,
//            'toPortCode' => $flight_line->arrive_port->code,
//            'mawbNumber' => $take_order->sn,
            'fromPortCode' => $this->data['fromPortCode'],
            'toPortCode' => $this->data['toPortCode'],
            'mawbNumber' => $this->data['mawbNumber']
        ];

        $res = $this->callApi($this->gatewayApiCode['delivery_line_haul_pre_booking_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['delivery_line_haul_pre_booking_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:中转-发车(glcTransitLinehaulDepartureCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function transit_line_haul_departure_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['transit_line_haul_departure_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['transit_line_haul_departure_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:出口清关开始(glcCustomsCcExStartCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function customs_cc_ex_start_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['customs_cc_ex_start_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['customs_cc_ex_start_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:出口清关失败(glcCustomsCcExFailureCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function customs_cc_ex_failure_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['customs_cc_ex_failure_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['customs_cc_ex_failure_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:出口清关完成(glcCustomsCcExSuccessCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function customs_cc_ex_success_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['customs_cc_ex_success_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['customs_cc_ex_success_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:干线交航失败(glcLineHaulHoAirlineFailedCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function line_haul_ho_airline_failed_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['line_haul_ho_airline_failed_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['line_haul_ho_airline_failed_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:干线异常(glcDeliveryLineHaulExceptionCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function delivery_line_haul_exception_callback($id, $exception_code = '', $returnToSc = false)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'opCode' => '0',
            'exceptionCode' => $exception_code,
            'returnToSc' => $returnToSc
        ];

        $res = $this->callApi($this->gatewayApiCode['delivery_line_haul_exception_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['delivery_line_haul_exception_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:干线交航成功(glcDeliveryLineHaulHoAirlineCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function delivery_line_haul_ho_airline_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $take_order = TakeOrderModel::find($order->take_order_id);
        if(!$take_order){
            return ['result' => false, 'msg' => '提单不存在'];
        }

        $flight = $take_order->flight;
        if(!$flight){
            return ['result' => false, 'msg' => '提单未配舱'];
        }


        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0',
            'fromPortCode' => $flight->start_port_code,
            'toPortCode' => $flight->arrive_port_code,
//            'fromPortCode' => $this->data['fromPortCode'],
//            'toPortCode' => $this->data['toPortCode'],
        ];

        $res = $this->callApi($this->gatewayApiCode['delivery_line_haul_ho_airline_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['delivery_line_haul_ho_airline_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:干线离开(glcDeliveryLineHaulDepartureCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function delivery_line_haul_departure_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['delivery_line_haul_departure_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['delivery_line_haul_departure_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:干线到达(glcDeliveryLineHaulArrivalCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function delivery_line_haul_arrival_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $receiver = json_decode($order->receiver, true);
        $opLocation = '';
        if($receiver){
            $opLocation = $receiver['address']['city'] ?? '';
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0',
            'opLocation' => $opLocation
        ];

        $res = $this->callApi($this->gatewayApiCode['delivery_line_haul_arrival_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['delivery_line_haul_arrival_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }


    /**
     * Notes:目的国清关开始(glcCustomsCcImStartCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function customs_cc_im_start_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['customs_cc_im_start_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['customs_cc_im_start_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:目的国清关失败(glcCustomsCcImAbnormalCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function customs_cc_im_abnormal_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['customs_cc_im_failure_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['customs_cc_im_failure_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:目的国清关完成(glcCustomsCcImSuccessCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function customs_cc_im_success_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['customs_cc_im_success_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['customs_cc_im_success_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:到达末端仓(glcCustomsHoOutSuccessCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function customs_ho_out_success_callback($id)
    {
        $order = OrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }

        $body = [
            'orderCode' => $order->orderCode,
            'opTime' => time(),
            'trackingNumber' => $order->trackingNumber,
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0'
        ];

        $res = $this->callApi($this->gatewayApiCode['customs_ho_out_success_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['customs_ho_out_success_callback'];
            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }

    /**
     * Notes:大包通用回告(glcCommonBigbagCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function common_bigbag_callback($id, $nodeCode = '', $activityCode = '')
    {
        $order = BigBagModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '订单不存在'];
        }


        $body = [
            'bigBagID' => $order->bigBagID,
//            'nodeCode' => $api->nodeCode,
//            'activityCode' => $api->activityCode,
            'nodeCode' => $nodeCode,
            'activityCode' => $activityCode,
            'opTime' => time(),
            'transportType' => '5',
            'operator' => $order->resCode,
            'opCode' => '0',
//            'fromPortCode' => '',
//            'toPortCode' => '',
//            'mawbNumber' => '',
        ];

        $res = $this->callApi($this->gatewayApiCode['common_bigbag_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['common_bigbag_callback'];
//            $log->orderCode = $order->orderCode;
            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }


    /**
     * Notes:提单信息回传(glcDeliveryLineHaulMawbCallback)
     * User: xiangzi
     * Date: 2025/5/13
     * Time: 下午2:25
     * @return array
     */
    public function delivery_line_haul_mawb_callback($id)
    {
        $order = TakeOrderModel::find($id);

        if(!$order){
            return ['result' => false, 'msg' => '提单不存在'];
        }

        $bigbag_ids = BigBagModel::where('take_order_id', $id)->pluck('bigBagID');

        $flight = FlightModel::with(['start_country', 'arrive_country'])->where('id', $order->flight_id)->first();

        if(!$flight){
            return ['result' => false, 'msg' => '航班信息不存在'];
        }

        $originalCountry = $flight->start_country->erzi_code ?? '';
        $originalPort = $flight->start_port_code;

        $destinationCountry = $flight->arrive_country->erzi_code ?? '';
        $destinationPort = $flight->arrive_port_code;

        $body = [
            'mawbNumber' => $order->sn,
            'originalCountry' => $originalCountry,
            'originalPort' => $originalPort,
            'destinationCountry' => $destinationCountry,
            'destinationPort' => $destinationPort,
            'opTime' => time(),
            'transportType' => '5',
            'bigBagIds' => $bigbag_ids,
        ];

//        $body = [
//            'mawbNumber' => $this->data['mawbNumber'],
//            'originalCountry' => $this->data['originalCountry'],
//            'originalPort' => $this->data['originalPort'],
//            'destinationCountry' => $this->data['destinationCountry'],
//            'destinationPort' => $this->data['destinationPort'],
//            'opTime' => time(),
//            'transportType' => '5',
//            'bigBagIds' => $this->data['bigBagIds']
//        ];

        $res = $this->callApi($this->gatewayApiCode['delivery_line_haul_mawb_callback'], [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = $order->customer_id;
            $log->msg_type = $this->gatewayApiCode['delivery_line_haul_mawb_callback'];
//            $log->orderCode = $order->orderCode;
//            $log->trackingNumber = $order->trackingNumber;
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '提单信息回传失败'];
        }

    }

    //签名
    public function sign($gatewayApiCode, $host, $uri, $accessKeyId, $accessKeySecret, $query, $body)
    {
        // 设置请求参数
        $headers["Host"] = $host;
        // date
        $date = gmdate('Y-m-d\TH:i:s\Z', time());
        $headers["x-acs-date"] = $date;

        $headers["x-acs-signature-nonce"] = uniqid();

        $headers["x-acs-action"] = $gatewayApiCode;
        $headers["x-acs-version"] = 'open_dchain1_0_0';

        // content Type
        $headers['Accept'] = 'application/json';
        $contentSha256 = '';
        $headers['Content-Type'] = 'application/json; charset=utf-8';

        $bodyStr = json_encode($body);
        $contentLength = strlen($bodyStr);
        if (!is_null($body) && $contentLength > 0) {
            $contentSha256 = hexHash($bodyStr);
            $headers["x-acs-content-sha256"] = $contentSha256;
        }

        $accept = $headers['Accept'];
        $contentType = $headers['Content-Type'];
        $headers["Content-Length"] = (string)$contentLength;
        $message = "POST\n" . $uri . "\n" ;
        //  query params
        if (sizeof($query) > 0) {
            $message .= '?';
        }
        ksort($query);
        $sep = '';
        foreach ($query as $key => $val) {
            $message .= $sep . $key . '=' . $val;
            $sep = '&';
        }

        $message .= "\naccept:" . $accept . "\ncontent-type:" . $contentType . "\nhost:" . $host . "\n";

        // header
        $filterHeaders = [];
        foreach ($headers as $key => $val) {
            if (strpos($key, 'x-acs-') === 0) {
                $filterHeaders[$key] = $val;
            }
        }
        ksort($filterHeaders);
        foreach ($filterHeaders as $key => $val) {
            $message .= $key . ':' . $val . "\n";
        }

        $signHeaders = 'accept;content-type;host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;' .
            'x-acs-version';
        $message .= "\n" . $signHeaders . "\n";
        $message .= $contentSha256;

        // signature & authorization
        $signMethod = 'ACS3-HMAC-SHA256';
        $stringToSign = $signMethod . "\n" . hexHash($message);
        $signature = bin2hex(hash_hmac('sha256', $stringToSign, $accessKeySecret, true));
        $auth = $signMethod . " " . "Credential=". $accessKeyId . "," .
            "SignedHeaders=" . $signHeaders . "," .
            "Signature=" . $signature;
        $headers['Authorization'] = $auth;
        return $headers;
    }

    //回传
    public function callApi($gatewayApiCode, $query, $body)
    {
        // 根据环境选择不同的域名
        // 预发：nbf-gateway-open-api.aidc-dchain.com
        // 正式：aidc-nbf.ap-southeast-1.aliyuncs.com
        $host = $this->host;
        $uri = '/open_dchain/1_0_0/' . lcfirst($gatewayApiCode);
        $url = 'https://' . $host . $uri;

        // 签名
        $headers = $this->sign(
            $gatewayApiCode,
            $host,
            $uri,
            config('lazada.AccessKeyId'),
            config('lazada.AccessKeySecret'),
            $query,
            $body
        );

        $headers_string = [];
        foreach ($headers as $param => $value) {
            $headers_string[] = "$param: $value";
        }

        //open connection
        $ch = curl_init();

        $fields_string = json_encode($body);

        //set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_string);

        //So that curl_exec returns the contents of the cURL; rather than echoing it
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function check(Request $request)
    {

        $id = $request->input('id');

        $data = LogModel::find($id);

        if(!$data){
            return $this->error('数据不存在');
        }

        $return = json_decode($data->data, true);

        return $this->success($return);
    }


    public function common_callback(Request $request)
    {
        $api_code = $request->input('gatewayApiCode');
        $body = $request->input('body');

        $body['opTime'] = time();
        $body['transportType'] = '5';
        $body['opCode'] = '0';


        $res = $this->callApi($api_code, [], $body);

        if($res){
            $log = New CallBackModel();
            $log->platform = 'lazada';
            $log->customer_id = 13;
            $log->msg_type = $api_code;
//            $log->orderCode = $order->orderCode;
            $log->trackingNumber = '';
            $log->opTime = time();
            $log->body = json_encode($body);
            $log->return = $res;
            $log->save();
            $res = json_decode($res,  true);
        }

        if($res && $res['success'] && $res['resultInfo']['resultStatus']){
            return ['result' => true];
        }else{
            return ['result' => false, 'msg' => '状态更新回传失败'];
        }

    }



}
